package cn.thornbird.orgsync.helper.token;

import cn.thornbird.orgsync.helper.WechatHelper;
import cn.thornbird.orgsync.model.certificate.WechatCertificate;
import cn.thornbird.orgsync.model.wechat.Token;
import cn.thornbird.orgsync.util.JsonUtil;

import java.util.HashMap;
import java.util.Map;

public class WechatToken extends AccessToken<WechatCertificate> {

    public WechatToken(String certificateText) {
        super(certificateText);
        Map<String, Object> map = JsonUtil.parseMap(certificateText);
        WechatCertificate certificate = new WechatCertificate();
        certificate.setCorpId(map.get("corpId").toString());
        certificate.setCorpSecret(map.get("corpSecret").toString());
        certificate.setAddressBookSecret(map.get("addressBookSecret").toString());
        this.certificate = certificate;
    }

    @Override
    protected String acquireToken() {
        String result = INVALID_TOKEN_TEXT.split(",")[0] + " " + INVALID_TOKEN_TEXT;
        String token = acquireToken(false);
        String addressBookToken = acquireToken(true);
        if (token.equals(INVALID_TOKEN_TEXT) || addressBookToken.equals(INVALID_TOKEN_TEXT)) {
            return result;
        }

        long milliseconds = Math.min(Long.parseLong(token.split(",")[1]),
                Long.parseLong(addressBookToken.split(",")[1]));
        result = token.split(",")[0] + " " + addressBookToken.split(",")[0] + "," + milliseconds;
        return result;
    }

    private String acquireToken(boolean addressBook) {
        String token = INVALID_TOKEN_TEXT;
        WechatHelper helper = new WechatHelper();
        helper.initialize(null, certificateText);
        Map<String, Object> uriVariables = new HashMap<>();
        uriVariables.put("corpid", certificate.getCorpId());
        uriVariables.put("corpsecret", addressBook ? certificate.getAddressBookSecret() : certificate.getCorpSecret());
        long now = System.currentTimeMillis();
        Token result = helper.doGet(WechatHelper.GET_TOKEN_PATH, uriVariables, null, Token.class);
        if (result != null && result.isSuccess()) {
            token = result.getAccessToken() + "," + (now + result.getExpiresIn() * 1000 + EXPIRATION_DELTA);
        }
        return token;
    }

}
